package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public TurnoverReportVO statisticalTurnover(LocalDate begin, LocalDate end) {

        /**
         * SELECT
         * 	sum( amount )
         * FROM
         * 	orders
         * WHERE
         * 	STATUS = 5
         * 	AND order_time > '2023-10-02 00:00:00'
         * 	AND order_time < '2023-10-02 23:59:59'
         *
         * 	411
         *
         * 	begin: 2023-10-01
         * 	end :  2023-10-07
         */
        //1,根据开始时间和结束时间计算出来中间的每一天时间存放在集合中
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);// 10-01
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        ArrayList<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //date表示每一天的时间日期  10-01  10-01 00:00:00  10-01 23:59:59
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end",endTime);
            //每一天的营业额
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        // 把两个集合编程字符串类型,并且每一个数据中间使用逗号分隔
        String dateStr = StringUtils.join(dateList, ",");
        String turnoverStr = StringUtils.join(turnoverList, ",");
        turnoverReportVO.setDateList(dateStr);
        turnoverReportVO.setTurnoverList(turnoverStr);
        return turnoverReportVO;
    }

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserReportVO userNumberStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建两个集合,分别装新增的用户数量和总的用户数量
        ArrayList<Integer> newUserList = new ArrayList<>();// 新增用户数
        ArrayList<Integer> totalUserList = new ArrayList<>();// 总用户数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // select count(*) from user where create_time > 10-01 00:00:00 and create_time < 10-01 23:59:59
            Integer newUserCount = getUserCount(beginTime, endTime);

            newUserList.add(newUserCount);
            // select count(*) from user where  create_time < 10-01 23:59:59
            Integer totalUserCount = getUserCount(null, endTime);
            totalUserList.add(totalUserCount);
        }



        return UserReportVO.builder()
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .dateList(StringUtils.join(dateList,","))
                .build();
    }

    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 根据传过来的参数,起始时间和结束时间计算中间的每一天,放在集合中
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //订单总数集合
        ArrayList<Integer> orderCountList = new ArrayList<>();
        //有效订单总数集合
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        // 遍历dateList集合,得到里面的每一天的数据 2023-10-01
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<Object, Object> map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",null);
            //获取每一天的订单总数量
            Integer TotalQuantity = orderMapper.countByMap(map);
            orderCountList.add(TotalQuantity);

            map.put("status",Orders.COMPLETED);
            Integer count = orderMapper.countByMap(map);
            validOrderCountList.add(count);
        }

        //计算订单总数量和有效订单总数量
        //订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }



        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /*
    SELECT
    od.name as name, sum(od.number) as number
    FROM
    order_detail as od,
    orders as o

    where od.order_id = o.id
    and o.status = 5
    and o.order_time >= '2023-10-01 00:00:00' and o.order_time <= '2023-12-11 23:59:59'
    GROUP BY name
    ORDER BY number desc
    limit 0,10;
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> top10List = orderMapper.top10(beginTime,endTime,Orders.COMPLETED);

        List<String> nameList = top10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = top10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        String nameStr = StringUtils.join(nameList, ",");
        String numberStr = StringUtils.join(numberList, ",");

        return new SalesTop10ReportVO(nameStr,numberStr);
    }

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 需要查询近30天内的数据,填充到模版文件中
     * @param httpServletResponse
     */
    @Override
    public void export(HttpServletResponse httpServletResponse) {
        //1,准备30天前的日期和1天前的日期
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //2,添加时分秒
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //3,查询近30天内的数据
        BusinessDataVO businessDataVO = workSpaceService.businessData(beginTime, endTime);

        try {
            //使用POI技术把数据填充到模板中
            FileInputStream fileInputStream = new FileInputStream("template\\运营数据报表模板.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
            //获取sheet页对象
            XSSFSheet sheet = excel.getSheetAt(0);
            //获取第2行的row对象
            XSSFRow row1 = sheet.getRow(1);
            row1.getCell(1).setCellValue(begin + "至" + end);


            //获取第4行的row对象
            XSSFRow row3 = sheet.getRow(3);

            XSSFCell cell2 = row3.getCell(2);
            cell2.setCellValue(businessDataVO.getTurnover());

            row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());

            row3.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获取第5行的row对象
            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row4.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO vo = workSpaceService.businessData(LocalDateTime.of(date, LocalTime.MIN),LocalDateTime.of(date, LocalTime.MAX));

                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(vo.getTurnover());
                row.getCell(3).setCellValue(vo.getValidOrderCount());
                row.getCell(4).setCellValue(vo.getOrderCompletionRate());
                row.getCell(5).setCellValue(vo.getUnitPrice());
                row.getCell(6).setCellValue(vo.getNewUsers());
            }



            //通过输出流将文件下载到浏览器中
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            excel.write(outputStream);


            excel.close();
            fileInputStream.close();
        } catch (Exception e){

        }
    }
}
